/*
Copyright [2020] [https://www.xiaonuo.vip]

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

  http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

Snowy采用APACHE LICENSE 2.0开源协议，您在使用过程中，需要注意以下几点：

1.请不要删除和修改根目录下的LICENSE文件。
2.请不要删除和修改Snowy源码头部的版权声明。
3.请保留源码和相关描述文件的项目出处，作者声明等。
4.分发源码时候，请注明软件出处 https://gitee.com/xiaonuobase/snowy
5.在修改包名，模块名称，项目代码等时，请注明软件出处 https://gitee.com/xiaonuobase/snowy
6.若您的项目无法满足以上几点，可申请商业授权，获取Snowy商业授权许可，请在官网购买授权，地址为 https://www.xiaonuo.vip
 */
package vip.xiaonuo.modular.attendanceshift.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang3.StringUtils;
import vip.xiaonuo.core.consts.CommonConstant;
import vip.xiaonuo.core.enums.CommonStatusEnum;
import vip.xiaonuo.core.exception.ServiceException;
import vip.xiaonuo.core.factory.PageFactory;
import vip.xiaonuo.core.pojo.page.PageResult;
import vip.xiaonuo.facedoor.modular.baseEntity.TreeNode;
import vip.xiaonuo.modular.attendancegroup.entity.AttendanceGroup;
import vip.xiaonuo.modular.attendancegroup.service.AttendanceGroupService;
import vip.xiaonuo.modular.attendancerecord.entity.AttendanceRecord;
import vip.xiaonuo.modular.attendancerecord.service.AttendanceRecordService;
import vip.xiaonuo.modular.attendanceshift.entity.AttendanceShift;
import vip.xiaonuo.modular.attendanceshift.enums.AttendanceShiftExceptionEnum;
import vip.xiaonuo.modular.attendanceshift.mapper.AttendanceShiftMapper;
import vip.xiaonuo.modular.attendanceshift.param.AttendanceShiftParam;
import vip.xiaonuo.modular.attendanceshift.service.AttendanceShiftService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import vip.xiaonuo.modular.attendanceshiftgroup.entity.AttendanceShiftGroup;
import vip.xiaonuo.modular.attendanceshiftgroup.service.AttendanceShiftGroupService;

import javax.annotation.Resource;
import java.util.*;

/**
 * 考勤班次service接口实现类
 *
 * @author JOE
 * @date 2022-11-11 15:33:48
 */
@Service
public class AttendanceShiftServiceImpl extends ServiceImpl<AttendanceShiftMapper, AttendanceShift> implements AttendanceShiftService {

    @Resource
    private AttendanceShiftGroupService groupService;

    @Resource
    private AttendanceGroupService attendanceGroupService;

    @Resource
    private AttendanceShiftService shiftService;

    @Resource
    private AttendanceRecordService recordService;

    @Override
    public PageResult<AttendanceShift> page(AttendanceShiftParam attendanceShiftParam) {
        QueryWrapper<AttendanceShift> queryWrapper = new QueryWrapper<>();
        if (ObjectUtil.isNotNull(attendanceShiftParam)) {

            // 根据班组ID 查询
            if (ObjectUtil.isNotEmpty(attendanceShiftParam.getAttendanceShiftGroupId())) {
                queryWrapper.lambda().eq(AttendanceShift::getAttendanceShiftGroupId, attendanceShiftParam.getAttendanceShiftGroupId());
            }
            // 根据班次名称 查询
            if (ObjectUtil.isNotEmpty(attendanceShiftParam.getShiftName())) {
                queryWrapper.lambda().like(AttendanceShift::getShiftName, attendanceShiftParam.getShiftName());
            }
        }
        return new PageResult<>(this.page(PageFactory.defaultPage(), queryWrapper));
    }

    @Override
    public List<AttendanceShift> list(AttendanceShiftParam attendanceShiftParam) {
        return this.list();
    }

    @Override
    public void add(AttendanceShiftParam attendanceShiftParam) {
        AttendanceShift attendanceShift = new AttendanceShift();
        BeanUtil.copyProperties(attendanceShiftParam, attendanceShift);
        this.save(attendanceShift);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void delete(AttendanceShiftParam attendanceShiftParam) {
        long num = recordService.count(new LambdaQueryWrapper<AttendanceRecord>()
                .eq(AttendanceRecord :: getAttendanceShiftId, attendanceShiftParam.getId())
                .gt(AttendanceRecord :: getEndDate , new Date())
                .isNull(AttendanceRecord :: getClockOutTime));

        if(num > 0){
            throw new ServiceException(500,"考勤记录中还有未完成的考勤计划，请先删除考勤计划，或过几天再来删除");
        }

        this.removeById(attendanceShiftParam.getId());
        List<AttendanceGroup> groups = attendanceGroupService.list();
        for(AttendanceGroup group : groups){
            this.removeDeletedId(group,attendanceShiftParam);
        }
        attendanceGroupService.saveOrUpdateBatch(groups);
    }

    private void removeDeletedId(AttendanceGroup group,AttendanceShiftParam param){
        String ids = group.getAttendanceShiftIds();
        String[] ids_arr = ids.split(",");
        List<String> id_list = Arrays.asList(ids_arr);
        String id = param.getId()+"";
        if(id_list.contains(id)){
            String result = "";
            String names = "";
            for(String s : id_list){
                if(s.equals(id)){
                    continue;
                }
                if(!result.equals("")){
                    result += ",";
                    names += ",";
                }
                result += s;
                AttendanceShift shift = shiftService.getById(s);
                names += StringUtils.isEmpty(shift.getShiftShortName()) ? shift.getShiftName() : shift.getShiftShortName();
            }
            group.setAttendanceShiftIds(result);
            group.setAttendanceShiftNames(names);
        }
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void edit(AttendanceShiftParam attendanceShiftParam) {
        AttendanceShift attendanceShift = this.queryAttendanceShift(attendanceShiftParam);
        BeanUtil.copyProperties(attendanceShiftParam, attendanceShift);
        this.updateById(attendanceShift);
    }

    @Override
    public AttendanceShift detail(AttendanceShiftParam attendanceShiftParam) {
        return this.queryAttendanceShift(attendanceShiftParam);
    }

    /**
     * 获取考勤班次
     *
     * @author JOE
     * @date 2022-11-11 15:33:48
     */
    private AttendanceShift queryAttendanceShift(AttendanceShiftParam attendanceShiftParam) {
        AttendanceShift attendanceShift = this.getById(attendanceShiftParam.getId());
        if (ObjectUtil.isNull(attendanceShift)) {
            throw new ServiceException(AttendanceShiftExceptionEnum.NOT_EXIST);
        }
        return attendanceShift;
    }

    @Override
    public List<TreeNode> listAll() {
        List<TreeNode> result = new ArrayList<>();
        List<AttendanceShiftGroup> groups = groupService.list(new LambdaQueryWrapper<AttendanceShiftGroup>().eq(AttendanceShiftGroup :: getIsEnable ,0));
        for(AttendanceShiftGroup group : groups){
            List<AttendanceShift> shifts = list(new LambdaQueryWrapper<AttendanceShift>().eq(AttendanceShift::getAttendanceShiftGroupId , group.getId()));
            if(shifts == null || shifts.size()==0){
                continue;
            }
            List<TreeNode> children = new LinkedList<>();
            for(AttendanceShift shift : shifts){
                TreeNode node = new TreeNode(Integer.parseInt(shift.getId()+""), StringUtils.isEmpty(shift.getShiftShortName()) ? shift.getShiftName() : shift.getShiftShortName());
                children.add(node);
            }
            TreeNode node = new TreeNode(Integer.parseInt("-"+group.getId()),group.getGroupName(),children);
            result.add(node);
        }
        return result;
    }
}
